package com.example.springbootyczy.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootyczy.DTO.CourseEditParamDTO;
import com.example.springbootyczy.DTO.CourseParamDTO;
import com.example.springbootyczy.entity.Course;
import com.example.springbootyczy.entity.ResultResponse;
import com.example.springbootyczy.service.ICourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(value = "/course")
public class CourseController{
    //注入service
    @Autowired
    ICourseService courseService;

    @PostMapping(value = "/page")
    public ResultResponse<List<Course>> page(@RequestBody CourseParamDTO param){
        //分页对象：包裹分页参数，页大小，当前页码
        Page<Course> page = new Page<Course>();
        page.setSize(param.getSize());
        page.setCurrent(param.getCurrent());

        //调用mybatis-plus进行分页查询
        Page<Course> dataPage = courseService.page(page, null);

        return ResultResponse.success("1000","成功", dataPage);
    }

    /**
     * 保存
     * @param course
     * @return
     */
    @PostMapping("/save")
    public ResultResponse save(@RequestBody Course course){
        boolean flag = courseService.save(course);
        return ResultResponse.success("1000", "成功", flag +"");
    }

    /**
     * 保存
     * @param editParamDTO
     * @return
     */
    @PostMapping("/edit")
    public ResultResponse updateById(@RequestBody CourseEditParamDTO editParamDTO){
        //对象属性值赋值：为空（null）的值不赋值
        Course course = BeanUtil.copyProperties(editParamDTO, Course.class);
        //更新
        boolean flag = courseService.updateById(course);
        //返回
        return ResultResponse.success("1000", "成功", flag +"");
    }
    /**
     * 删除
     * @param editParamDTO
     * @return
     */
    @PostMapping("/delete")
    public ResultResponse deleteById(@RequestBody CourseEditParamDTO editParamDTO){
        //按照id删除记录
        String id = editParamDTO.getId();
        //删除
        boolean flag = courseService.removeById(id);
        //返回
        return ResultResponse.success("1000", "成功", flag +"");
    }
}
